package com.erb.controller.llb;

import com.erb.common.Constant;
import com.erb.constants.CodepayConstants;
import com.erb.entity.CapitalLog;
import com.erb.entity.User;
import com.erb.service.llb.IOtherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class CodepayController {

	private static final Logger logger = LoggerFactory.getLogger(CodepayController.class);

	@Autowired
	IOtherService otherService;

	/**
	 * 支付
	 *
	 * @return
	 */
	@GetMapping("/pay")
	public void pay(Double price, @RequestParam(required = false, defaultValue = "3") int type, @SessionAttribute("user") User user, HttpServletResponse response) throws IOException {
		String url = "http://api2.xiuxiu888.com/creat_order/?";
		String return_url = "http://47.96.189.18:8080/erb/personal";
		//String notify_url = "http://localhost:8080/erb/notify";
		response.sendRedirect(url + "price=" + price + "&type=" + type + "&pay_id=" + user.getId() + "&page=" + CodepayConstants.PAGE + "&token=" + CodepayConstants.TOKEN + "&id=" + CodepayConstants.ID + "&return_url=" + return_url);
	}

	/**
	 * 同步验证支付结果
	 *
	 * @return
	 */
	@GetMapping("/personal")
	public void pay(HttpServletResponse response) throws IOException {
		String return_url = "http://47.96.189.18:8080/erb/per/index?option=2";
		//处理逻辑
		//......
		response.sendRedirect(return_url);
	}

	/**
	 * 异步验证支付结果
	 */
	@PostMapping("/notify")
	public String payNotify(HttpServletRequest request) throws NoSuchAlgorithmException {
		String key = CodepayConstants.KEY;
		Map<String, String> params = new HashMap<String, String>(); //申明hashMap变量储存接收到的参数名用于排序
		Map requestParams = request.getParameterMap(); //获取请求的全部参数
		String valueStr = ""; //申明字符变量 保存接收到的变量
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			valueStr = values[0];
			//乱码解决，这段代码在出现乱码时使用。如果sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);//增加到params保存
		}
		List<String> keys = new ArrayList<String>(params.keySet()); //转为数组
		Collections.sort(keys); //重新排序
		String prestr = "";
		String sign = params.get("sign"); //获取接收到的sign 参数

		for (int i = 0; i < keys.size(); i++) { //遍历拼接url 拼接成a=1&b=2 进行MD5签名
			String key_name = keys.get(i);
			String value = params.get(key_name);
			if (value == null || value.equals("") || key_name.equals("sign")) { //跳过这些 不签名
				continue;
			}
			if (prestr.equals("")) {
				prestr = key_name + "=" + value;
			} else {
				prestr = prestr + "&" + key_name + "=" + value;
			}
		}
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update((prestr + key).getBytes());
		String mySign = new BigInteger(1, md.digest()).toString(16).toLowerCase();
		if (mySign.length() != 32) {
			mySign = "0" + mySign;
		}
		logger.info("mySign:" + mySign);
		logger.info("sign:" + sign);
		if (mySign.equals(sign)) {
			logger.info("验证sign成功");
			String pay_no = request.getParameter("pay_no");//流水号
			int uid = Integer.parseInt(request.getParameter("pay_id"));//用户唯一标识
			String money = request.getParameter("money");//付款金额
			String price = request.getParameter("price");//订单原价

			Double tradeMoney = Double.parseDouble(price) * 1000000;
			otherService.updateUserBalance(uid, tradeMoney);
			logger.info("用户 " + uid + " 充值" + tradeMoney + "元成功");
			//添加资金记录
			CapitalLog capitalLog = new CapitalLog();
			capitalLog.setUid(uid);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
			capitalLog.setTradeDate(simpleDateFormat.format(new Date()));
			capitalLog.setTradeMoney(tradeMoney);
			capitalLog.setType(Constant.TRANSFER_IN_BALANCE);
			capitalLog.setRemark("充值余额");
			otherService.addCapitalLog(capitalLog);
			logger.info("添加资金记录成功");
			return "ok";
		} else {
			logger.info("参数不合法");
			//参数不合法
			return "fail";
		}
	}
}
